//
//  MessageCenterViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/7/22.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "MessageCenterViewController.h"
#import "MessageCenterTableViewCell.h"

static NSString * CellIndentfier = @"MessageCenterTableViewCell";

@interface MessageCenterViewController ()
<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UITableView *tableview;
@property(nonatomic,strong)NSMutableArray * noticesArray;

@end

@implementation MessageCenterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _noticesArray = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}

- (void)initViewLayout{
    
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    
    [self.tableview registerNib:[UINib nibWithNibName:CellIndentfier bundle:nil] forCellReuseIdentifier:CellIndentfier];
    
    self.view.backgroundColor = [UIColor colorWithWhite:0.957 alpha:1.000];
    
}


- (IBAction)back:(id)sender {
    [self backBtn];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableview.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
      
            int64_t delayInSeconds = 8.0;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                [self.tableview.header endRefreshing];
            });
            self.pageNO = 1;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //请求订单数据
                    [self getNoticeList];
            });
        
    }];
    // 马上进入刷新状态
    [self.tableview.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.noticesArray.count == _totle) {
        [self.tableview.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getNoticeList];
        });
    }
    
}


#pragma mark === 消息列表
- (void)getNoticeList{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:[NSNumber numberWithInteger:_pageNO] forKey:@"page"];
    [dic setObject:[NSNumber numberWithInteger:PageSize] forKey:@"pageSize"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallMessageList withHttpType:@"POST" withTag:JY_JY_mallMessageList];

}

#pragma mark  === 标记已读
- (void)readNotice{
    
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    
    NSInteger unRead = 0;
      NSString * unReadIds = @"";
    if (_noticesArray.count<=_unReadNum) {
        unRead = _noticesArray.count;
        for (int i = 0; i<unRead; i++) {
            NSString * unReadId = [NSString stringWithFormat:@"%@,",_noticesArray[i][@"mmesId"]];
            unReadIds = [unReadIds stringByAppendingString:unReadId];
        }
        
    }else{
        unRead = _unReadNum-(_pageNO-1)*10;
        for (int i = (_pageNO-1)*10; i<unRead; i++) {
            NSString * unReadId = [NSString stringWithFormat:@"%@,",_noticesArray[i][@"mmesId"]];
            unReadIds = [unReadIds stringByAppendingString:unReadId];
        }
    }
    if (unReadIds.length>0) {
        unReadIds = [unReadIds substringToIndex:unReadIds.length - 1];
    }
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msceMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:unReadIds forKey:@"museIds"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_markRead withHttpType:@"POST" withTag:JY_JY_markRead];

}


#pragma mark - <UITableViewDelegate && UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _noticesArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 120*VerticalRatio();
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MessageCenterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentfier];
    if (!cell) {
        cell = [[MessageCenterTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIndentfier];
    }
    cell.stateLabel.hidden = YES;
    if (indexPath.row+1<=_unReadNum) {
        cell.stateLabel.hidden = NO;
    }
    NSDictionary * dic = _noticesArray[indexPath.row];
    cell.timeLabel.text = [NSString stringWithFormat:@"%@",dic[@"mmesCreateTime"]];
    cell.detailLabel.text = [NSString stringWithFormat:@"%@",dic[@"mmesContent"]];
    
    if (indexPath.row == _noticesArray.count-1) {
        [self readNotice];
    }
    return cell;
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableview.header endRefreshing];
    [_tableview.footer endRefreshing];
    if (tag==JY_JY_mallMessageList) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"result"][@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableview.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableview.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.noticesArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"rows"];
                for (id entity in arr) {
                    [self.noticesArray addObject:entity];
                }
                
                [_tableview reloadData];
                
            });
        }
        
    }else if (tag == JY_JY_markRead){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }else {
            //设置推送消息个数
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableview.header endRefreshing];
    [_tableview.footer endRefreshing];
    [self dismissWaitDialog];
}



@end
